package com.starinside.wp.service.impl;

import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.ChildrenCouponCard;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.ext.aliyun.OSSProcessService;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.repository.ChildrenCouponCardRepository;
import com.starinside.wp.repository.ChildrenRepository;
import com.starinside.wp.service.UploadService;
import com.starinside.wp.utils.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.transaction.Transactional;
import java.io.*;
import java.nio.file.Files;
import java.util.Date;
import java.util.Objects;

/**
 * *******************************
 * Created by Tim.
 * form com.matt
 * on 2017/7/26
 * *******************************
 */
@Service
@Transactional
public class UploadServiceImpl implements UploadService {

    @Value("${aliyun.oss.filePathPrefix}")
    private String filePathPrefix;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;


    @Autowired
    private OSSProcessService fileProcessService;
    @Autowired
    private ChildrenCouponCardRepository childrenCouponCardRepository;

    @Autowired
    private ChildrenRepository childrenRepository;

    private static String getExtension(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        return extension;
    }

    @Override
    public String uploadStaticPhotoAlbum(String filePath) throws IOException {
        return uploadLocalFile(filePath, "photoalbum");
    }

    @Override
    public String uploadLocalFile(String url, String type) throws IOException{
        return uploadLocalFile(url, type, "");
    }

    public String uploadLocalFile(String url, String type, String prefix) throws IOException {
        File file = new File(url);
        FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());

        String uploadedResult = null;
        //写文件
        try {
            InputStream input = new FileInputStream(file);
            OutputStream os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            // Or faster..
            // IOUtils.copy(new FileInputStream(file), fileItem.getOutputStream());
            //上传oss
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

            if (type.equals("photoalbum")) {
                uploadedResult = uploadDailyFile("starfish", "photo_album/", multipartFile);
            }else{
                uploadedResult = uploadDailyFile(prefix + "_", type + "/", multipartFile);
            }
        } catch (IOException ex) {
            // do something.
            ex.printStackTrace();
        } finally {
            if(file.exists()){
                file.delete();
            }
        }

        return uploadedResult;
    }


    public String uploadMultiPartFiles(Integer type, String secondPath, String staffId, MultipartFile[] files) {
        String fileName = "";
        if (2 == type) {
            String originalName = files[0].getOriginalFilename();
            String extension = originalName.substring(originalName.lastIndexOf("."));
            fileName += DateUtil.millisToDateTime(System.currentTimeMillis(), "_yyyy-MM-dd_HH-mm-ss-SSS") + extension;
            String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + "/video/" + fileName, files[0]);
            return IMG_SERVICE_PREFIX + relativePath;
        } else if (1 == type) {
            String filePath = "";
            for (MultipartFile file : files) {
                fileName = "";
                String originalName = file.getOriginalFilename();
                String extension = originalName.substring(originalName.lastIndexOf("."));
                fileName += DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
                String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + "/img/" + fileName, file);
                filePath += IMG_SERVICE_PREFIX + relativePath + "|";
            }
            return StringUtils.substring(filePath, 0, filePath.length() - 1);
        }
        return null;
    }

    public String uploadDailyFile(String fileNamePrefix, String secondPath, MultipartFile file) {
        String extension = getExtension(file);
        String fileName = fileNamePrefix + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + secondPath + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM") + "/" + fileName, file);
        return IMG_SERVICE_PREFIX + relativePath;
    }

    @Override
    public String uploadCommonFile(String staffId, String type, MultipartFile file){
        String extension = getExtension(file);
        String fileName = staffId + "_"+ System.currentTimeMillis() + extension;
        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + "common/" + type + "/" + fileName, file);
        return IMG_SERVICE_PREFIX + relativePath;
    }

    @Override
    public String uploadComplaintRecordImg(String usersId, MultipartFile[] files) {
        return uploadMultiPartFiles(1, "complaint_record_wx", usersId, files);
    }

    @Override
    public String uploadFamilyRecordImg(String usersId, MultipartFile[] files) {
        return uploadMultiPartFiles(1, "family_feed_wx", usersId, files);
    }

    @Override
    public String uploadFamilyRecordVideo(String usersId, MultipartFile[] files) {
        return uploadMultiPartFiles(2, "family_feed_wx", usersId, files);
    }

    @Override
    public Children uploadChildrenHeadImg(String childrenId, MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String extension = originalName.substring(originalName.lastIndexOf("."));
        if (Objects.isNull(childrenId)){
            throw new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }
        Children children = childrenRepository.getOne(childrenId);
        if (Objects.isNull(children)){
            throw new BusinessException(ErrorCode.IS_TARGET, "宝宝不存在");
        }
        String fileName = children.getId() + "/" + DateUtil.millisToDateTime(System.currentTimeMillis(), "yyyy-MM-dd_HH-mm-ss-SSS") + extension;
        String relativePath = fileProcessService.aliyunOssUpload(filePathPrefix + "children/" + fileName, file);
        children.setImgUrl(IMG_SERVICE_PREFIX + relativePath);
        childrenRepository.save(children);
        return children;
    }

    @Override
    public Children updateCard(String childrenId, String card, String userName) {
        Children children = childrenRepository.getOne(childrenId);
        children.setCouponCard(card);
        childrenRepository.save(children);
        ChildrenCouponCard byChildrenIdAndCouponCard = childrenCouponCardRepository.findByChildrenIdAndCouponCard(childrenId, card);
        if (byChildrenIdAndCouponCard==null){
            throw new BusinessException(ErrorCode.IS_TARGET, "该优惠卷已使用");
        }
        ChildrenCouponCard couponCard=new ChildrenCouponCard();
        couponCard.setStatus(1);
        couponCard.setChildrenId(childrenId);
        couponCard.setCouponCard(card);
        couponCard.setUserName(userName);
        couponCard.setUseTime(new Date());
        childrenCouponCardRepository.save(couponCard);
        return children;
    }

}
